package com.sinvo.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinvo.oa.entity.model.system.SysRole;
import com.sinvo.oa.entity.model.system.SysUserRole;
import com.sinvo.oa.entity.vo.system.LoginVo;
import com.sinvo.oa.entity.vo.system.SysUserQueryVo;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.mapper.SysUserMapper;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinvo.oa.entity.model.system.SysUser;
import com.sinvo.oa.util.JwtUtils;
import com.sinvo.oa.util.LoginUserInfoUtils;
import com.sinvo.oa.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description SysUserService实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysPostService sysPostService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Page<SysUser> findUserByPage(Page<SysUser> page, SysUserQueryVo sysUserQueryVo) {
        //条件值
        String username = sysUserQueryVo.getKeyword();
        String createTimeBegin = sysUserQueryVo.getCreateTimeBegin();
        String createTimeEnd = sysUserQueryVo.getCreateTimeEnd();

        //封装条件，判断roleName是否为空
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //条件不为空
        if (!StringUtils.isEmpty(username)) {
            //封装 like模糊查询
            wrapper.like(SysUser::getUsername, username);
        }
        //时间范围
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge(SysUser::getCreateTime, createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.lt(SysUser::getCreateTime, createTimeEnd);
        }

        // 调用方法实现
        Page<SysUser> pageModel = this.page(page, wrapper);
        //records中没有 roleList属性 手动封装
        List<SysUser> records = pageModel.getRecords();

        records.stream().forEach(item -> {
            //复用方法 方法返回为map 需要强转
            List<SysRole> roleList = (List<SysRole>) sysRoleService.findRoleByUserId(item.getId()).get("assignedRoleList");
            //查询对应部门名
            String deptName = sysDeptService.getById(item.getDeptId()).getName();
            //查询对应岗位名
            String postName = sysPostService.getById(item.getPostId()).getName();
            item.setRoleList(roleList);
            item.setDeptName(deptName);
            item.setPostName(postName);
        });
        pageModel.setRecords(records);
        return pageModel;
    }

    @Override
    public void saveUser(SysUser user) {
        //封装条件 username唯一
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, user.getUsername());
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "用户名重复");
        }
        //获取密码
        String password = user.getPassword();
        //进行加密 再set回去
        String encrypt = MD5.encrypt(password);
        user.setPassword(encrypt);
        boolean success = this.save(user);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "保存失败，请重试");
        }
    }

    @Override
    public void updateUser(SysUser user) {
        //封装条件 username唯一
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, user.getUsername());
        SysUser one = this.getOne(queryWrapper);
        if (one != null && one.getId() != user.getId()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "用户名重复");
        }
        boolean success = this.updateById(user);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "更新失败，请重试");
        }
    }

    @Transactional
    @Override
    public boolean removeUser(Long id) {
        //删除用户
        this.removeById(id);
        //同时删除关系表数据
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId,id);
        sysUserRoleService.remove(queryWrapper);
        return true;
    }

    @Override
    public boolean changeStatus(Long id, Integer status) {
        //根据id获取用户
        SysUser user = this.getById(id);
        //修改状态
        user.setStatus(status);
        //更新
        this.updateById(user);
        return true;
    }

    @Override
    public String verify(LoginVo loginVo) {
        //获取username
        String username = loginVo.getUsername();
        //判断数据库是否有该用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = this.getOne(queryWrapper);
        //不存在
        if (sysUser == null) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "用户不存在");
        }
        //判断密码
        //数据库中的密码
        String pwd_db = sysUser.getPassword();
        //输入的密码
        String pwd_input = loginVo.getPassword();
        if (!pwd_db.equals(MD5.encrypt(pwd_input))) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "密码错误");
        }
        //判断status
        if (sysUser.getStatus() == 0) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "用户已被禁用");
        }
        //生成token
        String token = JwtUtils.createToken(sysUser.getId(), sysUser.getUsername());
        return token;
    }

    @Override
    public SysUser findUserByUserName(String username) {
        //封装条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = this.getOne(queryWrapper);
        return sysUser;
    }

    @Override
    public Map<String, Object> getCurrentUser() {
        SysUser sysUser = this.getById(LoginUserInfoUtils.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("name", sysUser.getName());
        map.put("phone", sysUser.getPhone());
        return map;
    }
}
